<style lang="scss" scoped>
    .join_lesson{
        position: relative;
        .go_center{
            position: absolute;
            right: 10px;
            top: 20px;
        }
    }
    .spill-gold{
        position: absolute;
        left: 0;right: 0;
        bottom: 0;top: 0;
        margin: auto;
        widows: 80vh;
        height: 80vh;

    }
    .currentGroup{
        border-bottom: 1px dashed $border-color;
        &:last-child{
            border:0
        }
    }
</style>
<template>
    <div class="join_lesson py-2 border-radius">
        <Button class="go_center" @click="go_center">返回个人中心</Button>
        <div v-if="!step">
            <h4 class="block-title">{{content.title}}</h4>
            <div class="mt-1 p-2">
                <div class="desp w-100b" style="word-break:break-all" v-html="content.content"></div>
                <div class="mt-2" v-if="content.file_list.length">
                    <span class="mr-1"> 附件列表：</span>
                    <download-list :file_list="content.file_list"/>
                </div>
                <div class="mt-4">
                    <Button @click="getAll_problems" type="primary" size="large">开始作答</Button>
                </div>
            </div>
        </div>
        <div class="problems p-1" v-else-if="step===1">
            <h4 class="block-title">题目树 <span class="color-999 font-12">（点击标题展示展示题目，点击上下箭头展示子节点）</span></h4>
            <Tree :data="treeData" ref="tree" @on-select-change="getNode" :render="treeRender"></Tree>
            <p class="font-12 mt-1 color-999 ml-1"><Icon type="ios-paper-outline" class="mr-1" color="#ff9900" />表示该节点尚有题目未作答，<Icon type="ios-paper-outline" class="mr-1" color="#19be6b"/>表示该节点所有题目已作答完毕。</p>
            <Divider>题目列表</Divider>
            <div v-if="active_node.id">
                <p class="text-center font-16 color-fff" v-if="!currentGroup.length">此节点下无题目</p>
                <div v-for="(value,index) in currentGroup" :key="index" class="mt-2 mb-1 currentGroup">
                    <div class="d-flex line-height-26">
                        <h4 class="block-title  mr-1">{{value.is_multi?'多选题':'单选题'}}</h4>
                        <!-- <span class="color-red" v-if="value.limit_time">限时 {{formateSeconds(limit_time)}}分钟</span> -->
                    </div>
                    <div class="details p-1">
                        <p class="mb-1">{{value.title}}</p>
                        <CheckboxGroup v-if="value.is_multi" v-model="currentGroupAnswer[index]" >
                            <Checkbox :disabled="value.disabled" class="d-block mb-1" :label="val.index" v-for="val in value.option" :key="val.index">{{val.index+'：'+val.text}}</Checkbox>
                        </CheckboxGroup>
                            <RadioGroup v-else vertical v-model="currentGroupAnswer[index]">
                                <Radio  :disabled="value.disabled" :label="val.index" v-for="val in value.option" :key="val.index">{{val.index+'：'+val.text}}</Radio>
                            </RadioGroup>
                        <div class="my-1" v-if="value.file_list.length">
                            <span class="mr-1">附件列表:</span>
                            <download-list :file_list="value.file_list"/>
                        </div>
                    </div>
                </div>
                
            </div>
            <Button type="primary" class="mb-2 ml-1" v-if="active_node.id" @click="submit_part" :disabled="active_node.finish">提交</Button>
        </div>
        <lesson-evaluate :lid="content.id" v-if="step==2" :modelFile="modelFile"  :is_last="content.is_last" @submit_complete="submit_complete"/>
        
        <div v-if="step===3" class="end">
            <img src="@/assets/spill-gold.gif" class="spill-gold" v-if="spill_gold_show">
            <h2 class="text-center  line-height-36">本次课程已结束</h2>
            <p class="text-center my-3">本节课有不懂的问题可以点击 <router-link :to="{path:'/s/questions_list',query:{tid:this.content.tid}}">这里</router-link> 向老师提问</p>
            <p class="mt-3 text-center font-16">本次作业得分率为{{accuracy}}%,共赢得 <span class="color-yellow">{{gold}}枚</span><Icon custom="iconfont icon-coin" size="18" class="color-yellow ml-1"/></p>

            <Button @click="reload" type="primary" size="large" class="mx-auto mt-5 d-block">再来一次</Button>
        </div>
        <audio ref="mp3" src="https://img.tukuppt.com/newpreview_music/08/98/74/5c88b757dd8dc88512.mp3"></audio> 
    </div>
</template>
<script>
    import {formateSeconds} from "@/common/tool"
    import {exam_questions,enter_lesson,submit_answers} from "@/common/sapi"
    import lessonEvaluate from "@/components/lessonEvaluate"
    // import downloadList from "@/components/downloadList"
    export default {
        inject: ['reload'],
        data(){
            return {
                formateSeconds,
                limit_timer:null,
                limit_time:0,
                spill_gold_show:true,
                step:0,
                content:{
                    file_list:[]
                },
                currentGroupAnswer:[],
                gold:0,
                accuracy:0,

                questions_list:[],
                currentGroup:[],
                treeData:[],
                active_node:{
                    id:'',
                    title:''
                },
                modelFile:[]
            }
        },
        methods:{
            getNode(){
                this.currentGroupAnswer=[]
                const node=this.$refs.tree.getSelectedNodes()
                if(node.length){
                    const {title,id,finish}=node[0]
                    this.active_node={id,title,finish}

                    this.currentGroup=this.questions_list.filter(el=>{
                        if(el.node_id===id){
                            this.currentGroupAnswer.push(el.is_multi?(el.tmp_answer?el.tmp_answer.split(','):[]):(el.tmp_answer || ''))
                            
                            return el
                        }
                    })
                }
            },
            treeRender(h, { data }){
                return h('span', {
                    style: {
                        display: 'inline-block',
                    }
                }, [
                    h('span', [
                        h('Icon', {
                            props: {
                                type: 'ios-paper-outline'
                            },
                            style: {
                                marginRight: '8px',
                                color:data.finish?'#19be6b':'#ff9900'
                            }
                        }),
                        h('span', data.title)
                    ]),
                    h('span', {
                        style: {
                            display: 'inline-block',
                            float: 'right',
                            marginRight: '32px'
                        }
                    })
                ]);
            },
            submit_part(){
                if(this.currentGroupAnswer.some(el=>Array.isArray(el)?!el.length:!el)){
                    this.$Notice.warning({
                        title: '提交失败',
                        desc: '还有题目未作答！'
                    });
                    return
                }
                const update_finish=(arr)=>{
                    arr.forEach((el,index)=>{
                        if(el.id===this.active_node.id)
                            this.$set(arr[index],'finish',true)
                        else
                            update_finish(el.children || [])
                    })
                }
                const diff_arr=(a, b)=>{
                    // 判断数组的长度
                    if (a.length !== b.length) {
                        return false
                    } else {
                        // 循环遍历数组的值进行比较
                        for (let i = 0; i < a.length; i++) {
                            if (a[i] !== b[i]) {
                                return false
                            }
                        }
                        return true;
                    }
                }
                update_finish(this.treeData)
                let complete=true
                this.questions_list.forEach((els,index)=>{
                    this.currentGroup.forEach( (el,i)=>{
                        if(el.id===els.id){
                            //找到已经作答的  题目列表 和当前组的题目，答案排序后放入题目列表
                            els.tmp_answer=Array.isArray(this.currentGroupAnswer[i])?this.currentGroupAnswer[i].sort((a,b)=>a.charCodeAt(0)-b.charCodeAt(0)).join(','):this.currentGroupAnswer[i]
                            this.$set(this.currentGroup[i],'disabled',true)
                            this.$set(this.questions_list[index],'disabled',true)
                        }
                    })
                    if(!els.tmp_answer)
                        complete=false
                })
                this.active_node.finish=true
                if(complete){
                    this.content.answers.forEach(el=>{
                        if(diff_arr(el.answers,this.questions_list.map(e=>e.tmp_answer))){
                            this.modelFile=el.files
                        }
                    })
                    this.step=2
                }else{
                    this.$Notice.success({
                        title: '提交成功',
                        desc: '作答成功，请选择其他主题！'
                    });
                }
                
            },
            submit_complete(data){
                const fm={
                    lid:this.content.id,
                    cid:localStorage.getItem('cid'),
                    teacher_evaluation:JSON.stringify(data[0]),
                    self_evaluation:JSON.stringify(data[1]),
                    answers:JSON.stringify(this.questions_list.map(e=>({qid:e.id,content:e.tmp_answer})))
                }
                submit_answers(fm)
                .then(res=>{
                    if(res){
                        this.gold=res.data.gold
                        this.accuracy=res.data.accuracy
                        this.step=3
                        this.$refs.mp3.play()
                        setTimeout(()=>this.spill_gold_show=false,4000)
                    }
                })
            },
            // process(val){
            //     clearInterval(this.limit_timer)
            //     if(val.limit_time){
            //         this.limit_time=val.limit_time*60
            //         this.limit_timer=setInterval(()=>{
            //             this.limit_time--
            //             if(this.limit_time<1){
            //                 clearInterval(this.limit_timer)
            //             }
            //         },1000)
            //     }
            //     this.currentProblems=val
            // },
            getAll_problems(){
                exam_questions({lid:this.content.id})
                .then(res=>{
                    if(res){
                        this.questions_list=res.data.question
                        this.step=1
                    }
                })
            },
            go_center(){
                 this.$Modal.confirm({
                    title: '确认',
                    content: `将退出当前作业，返回个人中心？`,
                    onOk: () => {
                        this.$router.push('center')
                    }
                });
            }
          
        },
        components:{
            lessonEvaluate,
            // downloadList
        },
        beforeDestroy(){
            //发送销毁http服务
        },
        created(){
            enter_lesson({lid:this.$route.query.lid})
            .then(res=>{
                if(res){
                    this.content=res.data.info
                    this.treeData=res.data.info.nodes
                }
            })
            // this.$ipcRenderer.send('active_topic')
            // this.$ipcRenderer.on('active_topic_reply',(event,data)=>{
            //     const index=this.questions_list.findIndex(el=>el.no==data)
            //     this.active_problems(index)
            //     this.$ipcRenderer.send('focus_main')
            // })
            
        }
    }
</script>